using System;

namespace MONA.Modules.Marketing.Controls
{
    public partial class AddEditAction : AddEditItemControl
    {
        public event EventHandler SaveClick;

        public bool Save()
        {
            int returnId = 0;
            if (Page.IsValid)
            {
                BLL.Action action = new BLL.Action();
                action.Name = txtActionName.Text.Trim();
                action.Description = txtDescription.Text.Trim();
                action.Function = txtFunction.Text.Trim();
                action.ChildActionID = Convert.ToInt32(ddlChildAction.SelectedValue);
                action.NextActionID = Convert.ToInt32(ddlNextAction.SelectedValue);
                
                if (this.ItemID == 0)
                {
                    returnId = action.Insert();
                }
                else
                {
                    action.ID = this.ItemID;
                    returnId = action.Update();
                }

                // Clear data in controls.
                txtActionName.Text = txtDescription.Text = txtFunction.Text = string.Empty;
                ddlChildAction.SelectedIndex = ddlNextAction.SelectedIndex = 0;
            }
            return returnId > 0;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            UpdateBar.Visible = this.ShowUpdateBar;
            btnDelete.Visible = this.ItemID > 0;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                if (this.ItemID > 0)
                {
                    BLL.Action action = BLL.Action.Load(this.ItemID);
                    if (action != null)
                    {
                        txtActionName.Text = action.Name;
                        txtDescription.Text = action.Description;
                        txtFunction.Text = action.Function;
                        ddlChildAction.SelectedValue = action.ChildActionID.ToString();
                        ddlNextAction.SelectedValue = action.NextActionID.ToString();
                    }
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.Save();
            if (SaveClick != null)
                SaveClick(sender, e);

            this.ReturnToReferrerPage();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            this.ReturnToReferrerPage();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.ItemID > 0)
            {
                BLL.Action action = new BLL.Action();
                action.ID = this.ItemID;
                action.Delete();
                this.ReturnToReferrerPage();
            }
        }
    }
}